<?php

namespace App\Models;

use App\Enums\PayChannel;
use App\Enums\TradeStatus;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class OnlineTradeOrder extends Model
{
    use HasFactory;

    use SoftDeletes;

    protected $fillable = [
        'order_no', 'order_ids', 'total_money', 'status', 'store_id'
    ];

    protected $casts = [
        'order_ids' => 'array',
        'status' => TradeStatus::class,
    ];

    public function store()
    {
        return $this->belongsTo(Store::class);
    }

    public function payed()
    {
        if ($this->status == TradeStatus::Payed)
            return;

        DB::transaction(function () {

            $this->status = TradeStatus::Payed;
            $this->save();

            Order::orderIdsPayed($this->order_ids, PayChannel::LeShua);
        });
    }

    public function wait()
    {
        $this->status = TradeStatus::Waiting;
        $this->save();
    }

    public function cancel()
    {
        $this->status = TradeStatus::Cancel;
        $this->save();
    }

    public static function genOrderNo()
    {
        return Order::generateOrderNo();
    }
}
